import * as turf from '@turf/turf';
/**
 * @desc 测绘类封装
 */
class MeasureTool {
  constructor(viewer) {
    this._viewer = viewer;
    this._map = viewer._map;
    this._L = viewer._L;
    // 要素组容器
    this._measureLayerMap = this._L.featureGroup();
    // 要素图层
    this._circleLayer = null;
    this._polylineLayer = null;
    this._polygonLayer = null;
    this._rectangleLayer = null; // 矩形图层
    // 每一个图形的实例
    this._circleInstance = null;
    this._polylineInstance = null;
    this._polygonInstance = null;
    this._rectangleInstance = null;
    // 初始化配置信息
    this.initDrawOptions(); // 初始化绘制工具
  }
  get view() {
    return this._viewer;
  }
  _clear() {
    this._measureLayerMap.clearLayers();
    this._circleLayer = null;
    this._polylineLayer = null;
    this._polygonLayer = null;
    this._rectangleLayer = null;
  }
  // 开始测绘圆形
  startDrawCircle(cb) {
    this._circleInstance = new this._L.Draw.Circle(this._map, {
      shapeOptions: {
        color: '#6bffff',
        fillColor: '#6bffff',
        fillOpacity: 0.5,
        opacity: 1,
        weight: 1,
      },
    });
    this._circleInstance.enable();
    this._map.on(this._L.Draw.Event.CREATED, (e) => {
      let layer = e.layer;
      if (layer) {
        this._circleLayer = layer;
        this._measureLayerMap.addLayer(this._circleLayer).addTo(this._map);
        // 计算面积圆
        let center = this._circleLayer._latlng;
        let radius = this._circleLayer?._mRadius || 0;
        let _area = (Math.PI * Math.pow(radius, 2)) / 1000000; // 单位为平方公里
        // 进行面积绘制label
        let options = {
          label: `测量面积为：${this._L.Util.formatNum(_area, 2)}km²`,
          positions: [center.lat, center.lng],
          labelType: 'default',
          operlayType: 'Circle',
          offsetX: 0,
          labelStyle: {
            fontSize: 12,
            paddingLR: 5,
            color: '#6bffff',
            opacity: 1,
          },
        };
        let labelLayer = new DX5S.LFTOverlay['CustomLabel'](options);
        this._measureLayerMap.addLayer(labelLayer);
        if (cb && typeof cb === 'function') {
          cb && cb(options);
        }
      }
    });
  }

  // 开始绘制多边形
  startDrawPolygon(cb) {
    this._polygonInstance = new this._L.Draw.Polygon(this._map, {
      shapeOptions: {
        color: '#6bffff',
        fillColor: '#6bffff',
        fillOpacity: 0.5,
        opacity: 1,
        width: 1,
      },
    });
    this._polygonInstance.enable();
    this._map.on(this._L.Draw.Event.CREATED, (e) => {
      let layer = e.layer;
      if (layer) {
        this._polygonLayer = layer;
        this._measureLayerMap.addLayer(this._polygonLayer).addTo(this._map);
        // 计算面积
        let areaNum = 0;
        let latLngs = this._polygonLayer.getLatLngs()[0];
        console.log('this._polygonLayer', this._polygonLayer);
        areaNum = this._L.GeometryUtil.geodesicArea(latLngs);
        // 设置面积单位为km
        areaNum = this._L.GeometryUtil.readableArea(areaNum, 'km');
        var center = this._polygonLayer?.getCenter();
        console.log('绘制多边形', areaNum, latLngs, center);
        // 进行面积绘制label
        let options = {
          label: `测量面积为：${areaNum}平方米`,
          positions: [center.lat, center.lng],
          labelType: 'default',
          operlayType: 'Polygon',
          offsetX: 0,
          labelStyle: {
            fontSize: 12,
            paddingLR: 5,
            color: '#6bffff',
            opacity: 1,
          },
        };
        let labelLayer = new DX5S.LFTOverlay['CustomLabel'](options);

        this._measureLayerMap.addLayer(labelLayer);
        if (cb && typeof cb === 'function') {
          cb && cb(options);
        }
      }
    });
  }

  // 开始绘制矩形
  startDrawRectangle(cb) {
    this._rectangleInstance = new this._L.Draw.Rectangle(this._map, {
      shapeOptions: {
        color: '#6bffff',
        fillColor: '#6bffff',
        fillOpacity: 0.5,
        opacity: 1,
        width: 1,
      },
    });
    this._rectangleInstance.enable();
    this._map.on(this._L.Draw.Event.CREATED, (e) => {
      let layer = e.layer;
      if (layer) {
        this._rectangleLayer = layer;
        this._measureLayerMap.addLayer(this._rectangleLayer).addTo(this._map);
        // 计算面积
        let areaNum = 0;
        let bounds = this._rectangleLayer.getBounds();
        areaNum =
          bounds.toBBoxString().split(',')[2] *
          bounds.toBBoxString().split(',')[3];
        // 设置面积单位为km
        areaNum = this._L.GeometryUtil.readableArea(areaNum, 'km');
        var center = this._rectangleLayer?.getBounds().getCenter();
        console.log('绘制矩形', areaNum, bounds);
        // 进行面积绘制label
        let options = {
          label: `测量面积为：${areaNum}平方米`,
          positions: [center.lat, center.lng],
          labelType: 'default',
          operlayType: 'Rectangle',
          offsetX: 0,
          labelStyle: {
            fontSize: 12,
            paddingLR: 5,
            color: '#6bffff',
            opacity: 1,
          },
        };
        let labelLayer = new DX5S.LFTOverlay['CustomLabel'](options);
        this._measureLayerMap.addLayer(labelLayer);
        if (cb && typeof cb === 'function') {
          cb && cb(options);
        }
      }
    });
  }

  // 开始绘制线
  startDrawPolyline(cb) {
    this._polylineInstance = new this._L.Draw.Polyline(this._map, {
      shapeOptions: {
        color: '#6bffff',
        fillColor: '#6bffff',
        fillOpacity: 0.5,
        opacity: 1,
        weight: 1,
      },
    });
    this._polylineInstance.enable();
    this._map.on(this._L.Draw.Event.CREATED, (e) => {
      let layer = e.layer;
      if (layer) {
        this._polylineLayer = layer;
        this._measureLayerMap.addLayer(this._polylineLayer).addTo(this._map);
        // 计算长度

        let latLngs = this._polylineLayer.getLatLngs();

        console.log('latLngs', latLngs);
        for (let i = 0; i < latLngs.length - 1; i++) {
          let distanceNum = 0;
          let labelLayer = null;
          if (latLngs[i + 1] && latLngs[i]) {
            distanceNum = this._map.distance(latLngs[i + 1], latLngs[i]) * 1;
            distanceNum = this._L.GeometryUtil.readableDistance(
              distanceNum,
              true,
              true,
              true,
              2,
            );
            console.log(
              'distanceNum',
              distanceNum,
              latLngs[i].lat,
              latLngs[i].lng,
            );
            labelLayer = new DX5S.LFTOverlay['CustomLabel']({
              label: `测量距离为：${distanceNum}公里`,
              positions: [latLngs[i + 1].lat, latLngs[i + 1].lng],
              labelType: 'default',
              operlayType: 'Polyline',
              offsetX: 0,
              labelStyle: {
                fontSize: 12,
                paddingLR: 5,
                color: '#6bffff',
                opacity: 1,
              },
            });
            console.log('labelLayer', labelLayer);
            this._measureLayerMap.addLayer(labelLayer);
          }
          if (cb && typeof cb === 'function') {
            cb &&
              cb({
                latLngs,
                label: `测量距离为：${distanceNum}公里`,
                positions: [latLngs[i].lat, latLngs[i].lng],
                area: distanceNum,
              });
          }
        }
      }
    });
  }
  // 初始化配置信息提示信息
  initDrawOptions() {
    if (this._L.drawLocal) {
      this._L.drawLocal.draw.handlers = {
        circle: {
          tooltip: {
            start: '点击并拖动以创建圆',
          },
          radius: '半径为',
        },
        marker: {
          tooltip: {
            start: '左键点击创建标记',
          },
        },
        polygon: {
          tooltip: {
            start: '左键点击开始绘制多边形',
            cont: '左键点击继续绘制多边形',
            end: '左键点击结束并锁定多边形',
          },
          error: {
            title: '多边形不符合要求',
            message: '请重新绘制多边形',
          },
        },
        polyline: {
          tooltip: {
            start: '左键点击开始绘制线',
            cont: '左键点击继续绘制线',
            end: '左键点击结束并锁定线',
          },
        },
        rectangle: {
          tooltip: {
            start: '左键点击并拖动以创建矩形',
          },
        },
        simpleshape: {
          tooltip: {
            end: '左键点击结束绘制并锁定',
          },
        },
      };
    }
  }

  // 移除绘制图形
  remove() {
    console.log('进来重绘了');
    this._clear();
    this.clearInstance();
    this._map.off(this._L.Draw.Event.CREATED);
  }

  // clear instance 清除实例
  clearInstance() {
    if (this._circleInstance) {
      this._circleInstance.disable();
      this._circleInstance = null;
    }
    if (this._rectangleInstance) {
      this._rectangleInstance.disable();
      this._rectangleInstance = null;
    }
    if (this._polylineInstance) {
      this._polylineInstance.disable();
      this._polylineInstance = null;
    }
    if (this._polygonInstance) {
      this._polygonInstance.disable();
      this._polygonInstance = null;
    }
  }

  // 转换经纬度坐标
  convertLatLng(latLng) {
    return this._map.latLngToLayerPoint(latLng);
  }
}
export default MeasureTool;
